#!/bin/bash
# DJVU_Cat_1.sh ( 21 ) This script , by Frank Trampe , joins multiple DjVu files into one large DjVu file .
# This script takes two arguments : the list of the input files ( in quotes , for example ) and the output file .

[ "x$TMPDIR" == x ] && TMPDIR=/tmp
tmpname="$TMPDIR/Electric_Document_$$.tmp"
mkdir -p "$tmpname" ;

let "Count_1 = 0" ;
for currentfile in $1 ; do
  if [ "$currentfile" != "" ] ; then
  Page_Count_1=`djvudump "$currentfile" | awk '{ count = 0 } /pages/ { for(i=2;i<=NF;i++){ if($i ~ "pages"){b=i-1; print $b}}}'` ;
  if [ "$Page_Count_1" -ge 0 ] ; then
    true ; # One must do something in an if block , and it never hurts to be positive .
    # echo "We have $Page_Count_1 pages ." ;
  else
    Page_Count_1=`djvudump "$currentfile" | awk 'BEGIN { count = 0 } /FORM:DJVU/ { count ++ } END { printf "%d" , count }'` ;
    true ;
    # echo "We have $Page_Count_1 pages ." ;
  fi
  let "Count_2 = 0" ;
    while [ "$Count_2" -lt "$Page_Count_1" ] ; do
    # echo Counts $Count_1 $Count_2 $Page_Count_1 ;
    let "Count_1 = Count_1 + 1" ;
    let "Count_2 = Count_2 + 1" ;
    djvused "$currentfile" -e "select $Count_2 ; save-page \"$tmpname/Page_"`printf "%04d" $Count_1`".C.djvu\" ;"
  done ;
  fi ;
done ;
djvm -c "$2" "$tmpname/Page_"????".C.djvu" ;

